//
//  IssuesViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 9/6/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit
import ReactiveCocoa


class IssuesViewController: UITableViewController {
    
    var viewModel: IssuesViewModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        
        viewModel.page.producer
            .filter { $0 > 0 }
            .start {
                data in
                self.tableView.reloadData()
            }
        
        viewModel.fetchIssues()
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.issues.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("IssueCell", forIndexPath: indexPath) as! IssueCell
        
        cell.entity = viewModel.issues[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    
    // MARK: - Navigation
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let indexPath = tableView.indexPathForSelectedRow
        let issueVC = segue.destinationViewController as! IssueViewController
        
        issueVC.viewModel = viewModel.issueViewModel(indexPath!)
    }
}
